import { IFileObj } from '@/type/file'

const mimeTypes = {
  doc: 'application/msword',
  docx: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
  ppt: 'application/vnd.ms-powerpoint',
  pptx: 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
  xls: 'application/vnd.ms-excel',
  xlsx: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
  pdf: 'application/pdf',
  png: 'image/png',
  jpg: 'image/jpeg',
  jpeg: 'image/jpeg',
  gif: 'image/gif',
  webp: 'image/webp',
}

// 获取文件后缀
export function getFileExt(fileName: string) {
  return fileName.slice(fileName.lastIndexOf('.')).toLowerCase()
}

// 下载文件
export function downloadFile(blob: Blob, fileName: string) {
  if (!blob || !fileName) return
  let elink = document.createElement('a')
  elink.download = fileName
  const ext = getFileExt(fileName).slice(1)
  const curMimeType = mimeTypes[ext]
  const newBlob = new Blob([blob], { type: curMimeType })
  const url = URL.createObjectURL(newBlob)
  elink.href = url
  elink.click()
  URL.revokeObjectURL(url)
  elink = null
}

// 拼接fileIdStr
export function getFileIdStr(fileList: IFileObj[]) {
  if (!fileList?.length) return ''
  return fileList
    .map((item: IFileObj) => item.id)
    .filter((id) => id)
    .join(',')
}

// 编辑时初始化文件列表
export function initIFileList(fileList: IFileObj[]) {
  if (!fileList?.length) return []
  return fileList.map((file: IFileObj) => {
    return {
      ...file,
      percentage: 100,
      name: file.name || file.orgFileName,
    }
  })
}

/**
 * 格式化字节数
 * @param bytes 字节数
 */
export function formatBytes(bytes: number) {
  const kb = bytes / 1024
  if (kb >= 1024) {
    return (kb / 1024).toFixed(2) + ' MB'
  } else {
    return kb.toFixed(2) + ' KB'
  }
}
